﻿using Koala.Pro.Common;
using Newtonsoft.Json;
using System.Net;
using System.Text;

namespace Koala.Pro.Helpers
{

    public static class ExtensionMethod
    {
        public static Dictionary<string, string> Clone(this Dictionary<string, string> dict)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> item in dict)
            {
                dictionary.Add(item.Key, item.Value);
            }
            return dictionary;
        }

        public static int ToInteger(this IPAddress IP)
        {
            byte[] addressBytes = IP.GetAddressBytes();
            return (addressBytes[0] << 24) | (addressBytes[1] << 16) | (addressBytes[2] << 8) | addressBytes[3];
        }

        public static int Compare(this IPAddress IP1, IPAddress IP2)
        {
            int num = ToInteger(IP1);
            int num2 = ToInteger(IP2);
            return (num - num2 >> 31) | (-(num - num2) >>> 31);
        }

        public static Dictionary<string, string> ToDictObject(this string jsonData)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(jsonData))
            {
                try
                {
                    result = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
                }
                catch (Exception ex)
                {
                    LogTextHelper.Error(ex);
                }
            }
            return result;
        }

        public static string ToJson(this Dictionary<string, string> dict)
        {
            return JsonConvert.SerializeObject(dict);
        }

        public static string ToDiplayString(this Dictionary<string, string> dict)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (string key in dict.Keys)
            {
                string text = dict[key];
                if (!string.IsNullOrEmpty(text))
                {
                    stringBuilder.AppendFormat("{0} /", text);
                }
            }
            return stringBuilder.ToString().Trim('/');
        }
    }

}
